<?php

require_once("../config.inc.php");
require_once("../classes/class.payment.php");
require_once('../includes/mailer.class.php');

$payment = new objPayment;
$discount = new objDiscount;
$discount->useDiscount($UserID);

$replyy = date("Y-m-d h:i:s")." -> "; //date for log file

// create vars for POST data
$reciever_eg = $_POST["PAYEE_ACCOUNT"];
$amount = $_POST["PAYMENT_AMOUNT"];
$units = $_POST["PAYMENT_UNITS"];
$metal = $_POST["PAYMENT_METAL_ID"];
//$amount = $_POST["PAYMENT_BATCH_NUM"];
$payer_eg = $_POST["PAYER_ACCOUNT"];
$invoice = $_POST["invoice"];
//$amount = $_POST["USD_PER_OUNCE"];
$payment_id = $_POST["PAYMENT_ID"];







if ($invoice) {
	// prepare event vars for DB
	$userID1 = explode("_",$invoice);
	$userID = $userID1[0];
	$subscrPeriod = $userID1[1];
	$subscr_type = $userID1[3];
	$subscrTime = time();
	$subscrID = $invoice;

	//check if DB record for this user exists
	$recordSet = $payment->db->Execute("SELECT u.Login FROM fa_subscriptions s LEFT JOIN fa_users u ON s.user_id=u.UserID WHERE s.user_id='$userID' and subscr_id='$invoice'");
	if ($recordSet) {
		while (!$recordSet->EOF) {			$payer_email = $recordSet->fields['Login'];
			$recordSet->MoveNext();
		}
	}
	$cnter = $recordSet->RecordCount();

	if (!$_GET['step']) $txn_type = "subscr_payment";
	else if ($_GET['step']=="success") $txn_type = "subscr_payment";
	else if ($_GET['step']=="fail") $txn_type = "subscr_failed";


	switch ($txn_type)   {
		case "subscr_payment":
			$activateSubscr = 1;
			//mail 2 us about new subscriber
			$payment->subscrNotify($payer_email,$userID,$subscrTime,$subscrPeriod,"subscr_new","E-gold"); // sends an email
			$discount->deactivateDiscount($userID);
			break;
		case "subscr_signup":
		case "subscr_failed":
		case "subscr_cancel":
		default:
			$activateSubscr = 0;
			break;
	}



		// insert or update subscription db record
	    if($cnter>0 ) {
			$recordSet = $payment->db->Execute("UPDATE fa_subscriptions SET subscr_status='$txn_type',subscr_type='$subscr_type',subscr_time='$subscrTime',subscr_active='$activateSubscr',subscr_period='$subscrPeriod' WHERE user_id='$userID' and subscr_id='$invoice'");
		} else {
	        $recordSet = $payment->db->Execute("INSERT INTO `fa_subscriptions` (user_id,subscr_id,subscr_time,subscr_status,subscr_type,subscr_active,subscr_period) VALUES('$userID','$subscrID','$subscrTime','$txn_type','$subscr_type','$activateSubscr','$subscrPeriod')");
		}
}

//////////////////////////////////////////////////////////////




//////////////////////////////////////////////////////////////
//// LOG ALL EVENTS ////
$replyy .= "IPN $payer_email | $txn_type | $invoice | $cnter | $info | $subscrID | $reciever_eg -> $payer_eg | pid $payment_id";
$fd = fopen("../logs/ipn_egold.log", "a");
fwrite($fd, $replyy."\r\n");
fclose($fd);


?>
